package com.teamsun.filter;

import com.teamsun.annotation.PrivateHandlerMethod;
import com.teamsun.util.Constants;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 通过对PrivateHandlerMethod注解的解析，判断相关的方法是否需要登录后才能访问
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        clearSession(request);

        if(handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            PrivateHandlerMethod privateHandler = handlerMethod.getMethod().getAnnotation(PrivateHandlerMethod.class);

            if (privateHandler != null) {
                // 验证是否登录
                if (!checkLogin(request)) {
                    request.getRequestDispatcher("/noSession").forward(request, response);
                    return false;
                }
            }
        }

        return super.preHandle(request, response, handler);
    }

    private boolean checkLogin(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(Constants.SESSION_USER);
        if (obj != null) {
            return true;
        } else {
            return false;
        }
    }

    private static List<String> needLoginReq = new ArrayList<String>();

    static {
        needLoginReq.add("/noSession");
    }

    private static void clearSession(HttpServletRequest request){
        String path = request.getServletPath();
        if(needLoginReq.contains(path)) {
            HttpSession session = request.getSession();
            session.removeAttribute(Constants.SESSION_USER);
            session.invalidate();
        }
    }
}
